package com.carsa.blackberry.ui.screen.gruposentregas;

import java.util.Calendar;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.component.SeparatorField;

import com.carsa.blackberry.CarsaApp;
import com.carsa.blackberry.MainKeys;
import com.carsa.blackberry.domain.dto.EntregaDTO;
import com.carsa.blackberry.domain.dto.ReasonDTO;
import com.carsa.blackberry.domain.dto.SecondReasonDTO;
import com.carsa.blackberry.domain.services.impl.EntregasServiceImpl;
import com.carsa.blackberry.domain.services.impl.GenericServiceImpl;
import com.carsa.blackberry.ui.UIKeys;
import com.carsa.blackberry.ui.screen.common.BasicScreen;
import com.carsa.blackberry.util.Util;
import com.carsa.blackberry.util.ui.UIUtil;
import com.carsa.blackberry.util.ui.widget.GridFieldManager;

/**
 * @author Nahuel Barrios.
 * @since 22/07/2010.
 * @version 1.0
 */
public class SeleccionarMotivoFallidaTotalScreen extends BasicScreen {

    private EntregaDTO        unaEntrega;

    private ObjectChoiceField _combo_reason;
    private ObjectChoiceField _combo_secondReason;

    private Hashtable         _pairsReasons = new Hashtable();

    public SeleccionarMotivoFallidaTotalScreen(EntregaDTO unaEntrega) {
	super(UIKeys.TITLE_SELECCIONAR_MOTIVO);
	super.customizeScreen();
	this.unaEntrega = unaEntrega;

	// Recupero los motivos de entrega fallida.
	Hashtable reasons = (Hashtable) CarsaApp.getMemory().get(MainKeys.PARAMETER_REASONS_AND_SUBREASONS);

	Vector reasonsVector = new Vector();
	Enumeration elements = reasons.elements();
	for (int idx = 0; elements.hasMoreElements(); idx++) {
	    ReasonDTO aReason = (ReasonDTO) elements.nextElement();

	    //	Chequeo que todos los submotivos NO tengan flepa seteado, para mostrar una razon.
	    boolean flag= true;
	    Vector subreasons = aReason.getSubreasons();
	    Enumeration subElements = subreasons.elements();
	    while (subElements.hasMoreElements()) {
		SecondReasonDTO secondReason = (SecondReasonDTO) subElements.nextElement();
		if (secondReason.isFlepaSetted())
		    flag= false;
	    }
	    
	    if(flag){
		reasonsVector.addElement(aReason.getReasonDescript());
		_pairsReasons.put(aReason.getReasonDescript(), aReason);
	    }
	}
	
	Object[] reasonsArray = new Object[reasonsVector.size()];
	reasonsVector.copyInto(reasonsArray);
	// ---
	
	_combo_reason = new ObjectChoiceField("", reasonsArray, 0, FIELD_RIGHT);
	_combo_reason.setChangeListener(new FieldChangeListener() {
	    public void fieldChanged(Field field, int context) {
		ReasonDTO selectedReason= (ReasonDTO) _pairsReasons.get(_combo_reason.getChoice(_combo_reason.getSelectedIndex()));
		_combo_secondReason.setChoices(filterSubreasonsFor(selectedReason.getReasonCode()));
	    }
	});
	_combo_secondReason = new ObjectChoiceField(""
		, this.filterSubreasonsFor(((ReasonDTO) _pairsReasons.get(reasonsArray[0])).getReasonCode())
		, 0
		, FIELD_RIGHT);

	super._bf_accept = new ButtonField(UIKeys.TITLE_ACCEPT, FIELD_LEFT);
	super._bf_accept.setChangeListener(new FieldChangeListener() {
	    public void fieldChanged(Field field, int context) {
		if (Util.getBooleanConditionFromDialogResponse(Dialog.ask(Dialog.D_YES_NO, UIKeys.POPUP_CONFIRMAR_OPERACION))) {
		    performSeleccionarMotivos();
		}
	    }
	});

	GridFieldManager grid_bottomToolbar = new GridFieldManager(2, 0);
	grid_bottomToolbar.add(_bf_accept);
	super.addBackButton(grid_bottomToolbar);

	// GridFieldManager grid_reason= new GridFieldManager(2, 0);
	// grid_reason.add(new LabelField(MainKeys.FIELD_REASON));
	// grid_reason.add(_combo_reason);
	//		
	// GridFieldManager grid_secondReason= new GridFieldManager(2, 0);
	// grid_secondReason.add(new LabelField(MainKeys.FIELD_SECOND_REASON));
	// grid_secondReason.add(_combo_secondReason);

	// ---------------------------------------------------
	// Con todos los controles ya seteados, armo la vista.
	_mainManager.add(new LabelField(UIKeys.FIELD_ENTREGA_FALLIDA_POR));
	_mainManager.add(UIUtil.getEmptyLine());

	_mainManager.add(new SeparatorField());
	_mainManager.add(new LabelField(UIKeys.FIELD_REASON));
	_mainManager.add(_combo_reason);
	_mainManager.add(new SeparatorField());
	_mainManager.add(new LabelField(UIKeys.FIELD_SECOND_REASON));
	_mainManager.add(_combo_secondReason);
	_mainManager.add(new SeparatorField());

	// add(grid_reason);
	// add(new SeparatorField());
	// add(grid_secondReason);

	UIUtil.addNewEmptyLine(_mainManager, 3);
	_mainManager.add(grid_bottomToolbar);
	this.add(_mainManager);
    }

    public Object[] filterSubreasonsFor(String reasonCode) {
	Hashtable reasons = (Hashtable) CarsaApp.getMemory().get(MainKeys.PARAMETER_REASONS_AND_SUBREASONS);

	ReasonDTO reason = (ReasonDTO) reasons.get(reasonCode);

	Vector subreasons = reason.getSubreasons();

	Object[] subreasonsArray = new Object[subreasons.size()];

	Enumeration elements = subreasons.elements();
	for (int idx = 0; elements.hasMoreElements(); idx++) {
	    SecondReasonDTO secondReason = (SecondReasonDTO) elements.nextElement();
	    subreasonsArray[idx] = secondReason.getDescript();
	}

	return subreasonsArray;
    }

    /**
     * Realiza todas las acciones vinculadas a la confirmacion del usuario de calificar la entrega como fallida.
     */
    public void performSeleccionarMotivos() {
	Hashtable parameters = new Hashtable();
	parameters.put(MainKeys.PARAMETER_DATE_TIME_MOMENT, Calendar.getInstance().getTime());

	// Seteo el submotivo
	ReasonDTO aReason= (ReasonDTO)_pairsReasons.get(_combo_reason.getChoice(_combo_reason.getSelectedIndex()));
	
	parameters.put(MainKeys.PARAMETER_REASON, aReason.getReasonCode());	
	
	// Obtengo el codigo a partir de la descripcion para el submotivo.
	Vector subreasons = new Vector();
	subreasons.addElement(_combo_secondReason.getChoice(_combo_secondReason.getSelectedIndex()));
	Vector subreasonsCodes = new GenericServiceImpl().doMappingWithSubreasons(subreasons);
	parameters.put(MainKeys.PARAMETER_SECOND_REASON, (String)subreasonsCodes.elementAt(0));
	
	// Finalmente ejecuto el servicio pasandole todos los parametros.
	new EntregasServiceImpl().markEntregaAsFail(unaEntrega, parameters, true);

	
	UiApplication.getUiApplication().popScreen(this);
	UiApplication.getUiApplication().pushScreen(new GruposEntregasScreen(true));
    }

    /**
     * Sobreescribo la funcionalidad por default que puse en BasicScreen para cada pantalla que tenga el boton "volver".
     * Hago esto, en este metodo porque el boton "volver" lo que hace cuando es presionado es llamar a este metodo.
     */
    public boolean onClose() {
	UiApplication.getUiApplication().popScreen(this);
	return false;
    }

}
